import os

import requests
# -*- coding:utf-8 -*-
import random
from lxml import etree
import threading
import requests
import json
import base64

from vne_erp.settings.dev1 import BASE_DIR


class Yuntu:
    """云途物流"""

    def __init__(self, ApiClientId, ApiSecre, ServerAddress='oms'):
        self.ApiClientId = ApiClientId  # 客户代码
        self.ApiSecret = ApiSecre  # 秘钥
        if ServerAddress == 'test':
            self.api = 'http://test.api.yunexpress.com/api/'  # 测试地址
        elif ServerAddress == 'oms':
            self.api = 'http://oms.api.yunexpress.com/api/'  # 正式地址
        self.Authorization = base64.b64encode(
            (self.ApiClientId + '&' + self.ApiSecret).encode()).decode()  # 用户认证的Token值
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
            'Authorization': 'Basic ' + self.Authorization,
            'Accept': 'application/json'
        }

    def getcountry(self):
        """查询国家简码"""
        response = requests.get(url=(self.api + '/Common/GetCountry'), headers=self.headers)
        return response.text

    def getshippingmethods(self, AD=None):
        """查询运输方式  AD代表具体国家简码"""
        if AD:
            response = requests.get(url=(self.api + 'Common/GetShippingMethods' + '?CountryCode={}'.format(AD)),
                                    headers=self.headers)
        else:
            response = requests.get(url=(self.api + 'Common/GetShippingMethods'), headers=self.headers)
        return response.text

    def createorder(self, data):
        """运单申请  data是json类型，示例:"""
        """ 
        [{
	"CustomerOrderNumber": "G2G20190402001",
	"ShippingMethodCode": "PK0004",
	"TrackingNumber": null,
	"TransactionNumber": null,
	"Height": 1,
	"Length": 1,
	"Width": 1,
	"PackageCount": 1,
	"Weight":1,
	"ApplicationType": 4,
	"ReturnOption": 0,
	"TariffPrepay": 0,
	"InsuranceOption": 0,
	"SourceCode": "API",
	"Receiver": {
		"CountryCode": "US",
		"FirstName": "xin",
		"LastName": "ming",
                "Company": "test gs",
		"Street":"67700 Lockwood-Jolon Road",
		"City": "Lockwood",
		"State": "California",
		"Zip":"93932",
		"Phone": "5869098233",
		"HouseNumber": "1"
	},
	"Sender": {
		"CountryCode": "US",
		"FirstName": "test",
		"LastName": "ming",
                "Company": "test gs",
		"Street": "207 TELLURIDE DR",
		"City": "GEORGETOWN",
		"State": "TX",
		"Zip": "78626-7163",
		"Phone": "5869098233",
		"HouseNumber": "1"
	},
	"Parcels": [{
		"EName": "shangpin1",
		"CName": "商品1",
		"HSCode": null,
		"Quantity": 1,
		"SKU": "sku1001",
		"UnitPrice":10,
		"UnitWeight":1,
		"Remark": "商品",
		"InvoiceRemark": "ceshi 1 pcs",
		"CurrencyCode": null
	}],
	"ChildOrders": [{
		"BoxNumber": "test01",
		"Length": 1,
		"Width": 1,
		"Height": 1,
		"BoxWeight": 1,
		"ChildDetails": [{
			"Sku": "sku1001",
			"Quantity": 1
		}]
	}]
}]
"""
        headers = self.headers
        headers['Content-Type'] = 'application/json'
        response = requests.post(url=self.api + 'WayBill/CreateOrder', headers=headers, data=data)
        return response.text

    def labelprint(self, data):
        """标签(面单）打印  data是json类型"，示例：["YT1907911202000015"]"""
        headers = self.headers
        headers['Content-Type'] = 'application/json'
        response = requests.post(url=self.api + 'Label/Print', headers=headers, data=data)
        return response.text

    def gettrackingnumber(self,data):
        """查询跟踪号  data示例：['113-8798945-8445813','112-4234610-5801032]'"""
        url = self.api + '/Waybill/GetTrackingNumber?CustomerOrderNumber='
        for i in data:
            url += ','+i
        headers = self.headers
        response = requests.get(url,headers=headers)
        result =json.loads(response.text)
        items = result.get('Items')
        if items:
            return items
        else:
            return {'Message':'未找到数据'}


class ImageMethod:
    def __init__(self):
        self.file_path = os.path.join(BASE_DIR, 'apps/orders/image_need_file/proxy_list')
        self.USER_AGENT = [
        "Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1;AcooBrowser;.NETCLR1.1.4322;.NETCLR2.0.50727)",
        "Mozilla/4.0(compatible;MSIE7.0;WindowsNT6.0;AcooBrowser;SLCC1;.NETCLR2.0.50727;MediaCenterPC5.0;.NETCLR3.0.04506)",
        "Mozilla/4.0(compatible;MSIE7.0;AOL9.5;AOLBuild4337.35;WindowsNT5.1;.NETCLR1.1.4322;.NETCLR2.0.50727)",
        "Mozilla/5.0(Windows;U;MSIE9.0;WindowsNT9.0;en-US)",
        "Mozilla/5.0(compatible;MSIE9.0;WindowsNT6.1;Win64;x64;Trident/5.0;.NETCLR3.5.30729;.NETCLR3.0.30729;.NETCLR2.0.50727;MediaCenterPC6.0)",
        "Mozilla/5.0(compatible;MSIE8.0;WindowsNT6.0;Trident/4.0;WOW64;Trident/4.0;SLCC2;.NETCLR2.0.50727;.NETCLR3.5.30729;.NETCLR3.0.30729;.NETCLR1.0.3705;.NETCLR1.1.4322)",
        "Mozilla/4.0(compatible;MSIE7.0b;WindowsNT5.2;.NETCLR1.1.4322;.NETCLR2.0.50727;InfoPath.2;.NETCLR3.0.04506.30)",
        "Mozilla/5.0(Windows;U;WindowsNT5.1;zh-CN)AppleWebKit/523.15(KHTML,likeGecko,Safari/419.3)Arora/0.3(Change:287c9dfb30)",
        "Mozilla/5.0(X11;U;Linux;en-US)AppleWebKit/527+(KHTML,likeGecko,Safari/419.3)Arora/0.6",
        "Mozilla/5.0(Windows;U;WindowsNT5.1;en-US;rv:1.8.1.2pre)Gecko/20070215K-Ninja/2.1.1",
        "Mozilla/5.0(Windows;U;WindowsNT5.1;zh-CN;rv:1.9)Gecko/20080705Firefox/3.0Kapiko/3.0",
        "Mozilla/5.0(X11;Linuxi686;U;)Gecko/20070322Kazehakase/0.4.5",
        "Mozilla/5.0(X11;U;Linuxi686;en-US;rv:1.9.0.8)GeckoFedora/1.9.0.8-1.fc10Kazehakase/0.5.6",
        "Mozilla/5.0(WindowsNT6.1;WOW64)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11",
        "Mozilla/5.0(Macintosh;IntelMacOSX10_7_3)AppleWebKit/535.20(KHTML,likeGecko)Chrome/19.0.1036.7Safari/535.20",
        "Opera/9.80(Macintosh;IntelMacOSX10.6.8;U;fr)Presto/2.9.168Version/11.52",
        "Mozilla/5.0(WindowsNT6.1;WOW64)AppleWebKit/536.11(KHTML,likeGecko)Chrome/20.0.1132.11TaoBrowser/2.0Safari/536.11",
        "Mozilla/5.0(WindowsNT6.1;WOW64)AppleWebKit/537.1(KHTML,likeGecko)Chrome/21.0.1180.71Safari/537.1LBBROWSER",
        "Mozilla/5.0(compatible;MSIE9.0;WindowsNT6.1;WOW64;Trident/5.0;SLCC2;.NETCLR2.0.50727;.NETCLR3.5.30729;.NETCLR3.0.30729;MediaCenterPC6.0;.NET4.0C;.NET4.0E;LBBROWSER)",
        "Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1;QQDownload732;.NET4.0C;.NET4.0E;LBBROWSER)",
        "Mozilla/5.0(WindowsNT6.1;WOW64)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.84Safari/535.11LBBROWSER",
        "Mozilla/4.0(compatible;MSIE7.0;WindowsNT6.1;WOW64;Trident/5.0;SLCC2;.NETCLR2.0.50727;.NETCLR3.5.30729;.NETCLR3.0.30729;MediaCenterPC6.0;.NET4.0C;.NET4.0E)",
        "Mozilla/5.0(compatible;MSIE9.0;WindowsNT6.1;WOW64;Trident/5.0;SLCC2;.NETCLR2.0.50727;.NETCLR3.5.30729;.NETCLR3.0.30729;MediaCenterPC6.0;.NET4.0C;.NET4.0E;QQBrowser/7.0.3698.400)",
        "Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1;QQDownload732;.NET4.0C;.NET4.0E)",
        "Mozilla/4.0(compatible;MSIE7.0;WindowsNT5.1;Trident/4.0;SV1;QQDownload732;.NET4.0C;.NET4.0E;360SE)",
        "Mozilla/5.0(WindowsNT5.1)AppleWebKit/537.1(KHTML,likeGecko)Chrome/21.0.1180.89Safari/537.1",
    ]

        self.useable_set = set()

    def get_ip(self,url):
        headers = {'User-Agent': random.choice(self.USER_AGENT)}
        response = requests.get(url, headers=headers)
        content = etree.HTML(response.text)
        lists = content.xpath("//tbody/tr")
        if lists:
            for li in lists:
                ip = li.xpath("./td[1]/text()")
                if len(ip):
                    ip = li.xpath("./td[1]/text()")[0].strip()
                    port = li.xpath("./td[2]/text()")[0].strip()
                    ip_proxy = ip + ":" + port
                    self.useable_set.add(ip_proxy)
        else:
            return None

    #调用save_start来进行爬取ip并保存在本地
    def save_start(self):
        thread_list = []
        for i in range(20):
            url = f"http://www.89ip.cn/index_{i}.html"
            t = threading.Thread(target=self.get_ip, args=(url,))
            thread_list.append(t)
        [th.start() for th in thread_list]
        [th.join() for th in thread_list]
        with open(self.file_path, "w+", encoding="utf-8") as f:
            for item in self.useable_set:
                f.write(f"{item}\n")


    def ip_test(self, url,proxy=None,timeout=10):
        headers = {'User-Agent': random.choice(self.USER_AGENT)}
        try:
            proxy = {
                'http': proxy,
            }
            r = requests.get(url,headers=headers,timeout=timeout, proxies=proxy) if proxy != None else requests.get(url,headers=headers,timeout=timeout)
            return r.text
        except Exception as e:
            # print(f"error with url:{e}")
            return None

    useable_list = []
    #调用ip_run来进行ip测试清洗
    def ip_deal(self, url, proxy):

        data = self.ip_test(url, proxy=proxy)
        if data == None:
            # print("该ip不可用：", proxy)
            pass
        else:
            self.useable_list.append(proxy)


    def ip_run(self):
        ip_list = []
        with open(self.file_path, "r", encoding="utf-8") as f:
            lines = f.readlines()
            for line in lines:
                ip_list.append(line.strip())
        thread_list = []
        for i in ip_list:
            t = threading.Thread(target=self.ip_deal, args=("http://httpbin.org/get?x=2&y=4", i))
            thread_list.append(t)
        [th.start() for th in thread_list]
        [th.join() for th in thread_list]
        with open(self.file_path, "w+", encoding="utf-8")as f:
            for i in self.useable_list:
                f.write(f"{i}\n")
        print("程序结束！！！")

